<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择供应商"
    width="80%"
    destroy-on-close
  >
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" label-width="90px" class="search-area">
      <!-- 第一行 -->
      <el-form-item label-width="0">
        <div style="display: flex; gap: 12px;">
          <el-form-item label="供应商名称:"/>
          <el-input
            v-model="queryParams.name"
            placeholder="请输入供应商名称"
            clearable
            style="width: 300px"
            @keyup.enter="handleQuery"
          />
          <el-form-item label="供应商分类"/>
          <el-select
  v-model="queryParams.supplierClassName" 
  placeholder="请选择分类"
  clearable
  style="width: 240px"
  :loading="classLoading"
>
  <el-option 
    v-for="item in supplierClassOptions" 
    :key="item.code" 
    :label="item.name" 
    :value="item.name"  
  />
</el-select>
        </div>
      </el-form-item>

      <!-- 第二行 -->
      <el-row :gutter="20" class="mt-2">
        <el-col :span="12">
          <el-form-item label="供应商编号">
            <el-input 
              v-model="queryParams.code" 
              placeholder="请输入供应商编号" 
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <div class="btn-group">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table
      :data="pagedTableData"
      v-loading="loading"
      :header-cell-style="{ background: '#f5f7fa', color: '#333' }"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="code" label="供应商编号" align="center" />
      <el-table-column prop="name" label="供应商名称" align="center" />
      <el-table-column prop="supplierClassCode" label="供应商分类" align="center">
  <template #default="{ row }">
    {{ row.supplierClassCode }}  <!-- 直接显示名称 -->
  </template>
</el-table-column>

      <el-table-column prop="country" label="国家地区" align="center" />
    </el-table>

    <!-- 分页器：右下角 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="filteredDataCount"
        :page-size="queryParams.pageSize"
        v-model:current-page="queryParams.pageNo"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="footer-left">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { SupplierInfoVO } from '@/api/product/supplierinfo/index'
import  {SupplierInfoApi} from '@/api/product/supplierinfo/index' // 请根据实际路径调整
const emit = defineEmits(['select'])

// 定义供应商分类类型
interface SupplierClass {
  code: string;
  name: string;
}

const classMap = ref(new Map<string, string>())

// 加载状态
const loading = ref(false)
const classLoading = ref(false) // 专门用于分类加载状态
const dialogVisible = ref(false)

// 供应商数据
const allSupplierData = ref<SupplierInfoVO[]>([]) 
const selectedSuppliers = ref<SupplierInfoVO[]>([])

// 供应商分类数据
const supplierClasses = ref<SupplierClass[]>([])

// 查询参数
const queryParams = reactive({
  name: '',
  supplierClassName: '',  // 修改为分类名称
  code: '',
  pageNo: 1,
  pageSize: 10
})

// 计算属性：供应商分类选项（用于下拉框）
const supplierClassOptions = computed(() => {
  return supplierClasses.value
})

// 获取分类名称（修改后）
const getClassLabel = (code: string) => {
  return classMap.value.get(code) || code
}

// 计算属性：过滤后的数据（修正筛选逻辑）
const filteredData = computed(() => {
  return allSupplierData.value.filter(item => {
    const nameMatch = !queryParams.name || 
      (item.name && item.name.toLowerCase().includes(queryParams.name.toLowerCase()))
    
    const codeMatch = !queryParams.code || 
      (item.code && item.code.toLowerCase().includes(queryParams.code.toLowerCase()))
    
    // 关键修改：使用分类名称直接匹配
    const typeMatch = !queryParams.supplierClassName || 
      item.supplierClassCode === queryParams.supplierClassName
    
    return nameMatch && codeMatch && typeMatch
  })
})

// 计算过滤后的数据总数
const filteredDataCount = computed(() => filteredData.value.length)

// 计算属性：分页后的数据
const pagedTableData = computed(() => {
  const start = (queryParams.pageNo - 1) * queryParams.pageSize
  const end = start + queryParams.pageSize
  return filteredData.value.slice(start, end)
})

// 获取供应商分类
// 获取供应商分类
// 获取供应商分类（修改后）
const fetchSupplierClasses = async () => {
  try {
    classLoading.value = true
    const res = await SupplierInfoApi.getSupplierClassList()
    
    // 重置映射
    const newMap = new Map<string, string>()
    
    if (Array.isArray(res)) {
      res.forEach(item => {
        if (item.code && item.type) {
          newMap.set(item.code, item.type)
        }
      })
    } 
    // 处理其他可能的响应结构...
    
    classMap.value = newMap
    supplierClasses.value = Array.from(newMap, ([code, name]) => ({
      code,
      name
    }))
    
    console.log('分类映射表:', classMap.value)
  } catch (error) {
    console.error('❌ 获取供应商分类失败:', error)
    ElMessage.error('获取供应商分类失败')
  } finally {
    classLoading.value = false
  }
}
// 在打开弹窗时确保分类数据加载
const open = (suppliers: SupplierInfoVO[]) => {
  allSupplierData.value = suppliers
  dialogVisible.value = true
  resetQuery()
  
  // 强制重新加载分类数据
  fetchSupplierClasses()
  
  // 调试：打印表格中的分类代码
  console.log('表格中的供应商分类代码:', 
    [...new Set(suppliers.map(s => s.supplierClassCode))]
  )
}

// 分页变化处理
const handlePageChange = (page: number) => {
  queryParams.pageNo = page
}

// 选择变化处理
const handleSelectionChange = (selection: SupplierInfoVO[]) => {
  selectedSuppliers.value = selection
}

// 查询处理
const handleQuery = () => {
  loading.value = true
  // 重置到第一页
  queryParams.pageNo = 1
  
  // 模拟加载效果
  setTimeout(() => {
    loading.value = false
  }, 300)
}

// 重置查询条件
const resetQuery = () => {
  queryParams.name = ''
  queryParams.supplierClassCode = ''
  queryParams.code = ''
  queryParams.pageNo = 1
  handleQuery()
}

// 确认选择
const handleConfirm = () => {
  if (selectedSuppliers.value.length === 0) {
    ElMessage.warning('请至少选择一个供应商')
    return
  }
  
  // 将选中的供应商传回父组件
  emit('select', selectedSuppliers.value[0])
  
  dialogVisible.value = false
}
defineExpose({ open })
</script>

<style scoped>
.search-area {
  margin-bottom: 20px;
}

.btn-group {
  display: flex;
  gap: 10px;
  margin-top: 2px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.footer-left {
  display: flex;
  justify-content: flex-start;
}

.mt-2 {
  margin-top: 8px;
}
</style>